<template>
  <div v-show="vMode === 'home'">
    <van-nav-bar title="财务客体" left-text="返回" left-arrow @click-left="goHome" fixed>
      <template #right>
        <van-icon name="ellipsis" size="18" @click="home.toolBtn = true" />
      </template>
    </van-nav-bar>
    <p style="margin-top: 40px"></p>
    <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" offset="10" @load="onLoad">
      <!--@todo tab 显示用信息-->
      <van-cell v-for="item in vList" :key="item.id" :label="`${item.full_name} 最近更新： ${item.mtime}`"
        :value="`${item.is_master ? '主体' : '客体'}`" @click="
          vMode = 'view';
        vRow = item;
        " is-link>
        <template #title>
          <span class="custom-title">{{ item.name }}</span>
        </template>
      </van-cell>
    </van-list>
    <!-- 主页工具栏弹出框 -->
    <van-action-sheet v-model:show="home.toolBtn" :actions="home.tools" cancel-text="取消" close-on-click-action
      @cancel="home.toolBtn = false" @select="onHomeToolSel" />
    <!-- 搜索对话框 -->
    <van-dialog v-model:show="home.search.show" title="客体搜索" show-cancel-button @confirm="onSearch">
      <van-search v-model="home.search.value" placeholder="请输入搜索关键词" @keydown="onSearchKeydown" />
    </van-dialog>
  </div>
  <div v-show="vMode === 'view'">
    <van-nav-bar :title="vRow.name" left-text="返回" left-arrow @click-left="vMode = 'home'" />
    <van-cell center title="名称" :value="vRow.name" />
    <van-cell center title="全称" :value="vRow.full_name" />
    <van-cell center title="编号" :value="vRow.code_number" />
    <van-cell center title="是否主体" :value="`${vRow.is_master ? '是' : '否'}`" />
    <van-cell center title="使用在使用" :value="`${vRow.use_mk ? '是' : '否'}`" />
    <van-cell center title="口令" :value="`${vRow.has_command ? '******（点击查看）' : '未设置'}`" :is-link="!!vRow.has_command" />
    <van-cell center title="备注" :label="vRow.remark" />
    <van-cell center title="编辑时间" :value="vRow.mtime" />
    <van-cell center title="创建时间" :value="vRow.ctime" />
    <div style="margin: 16px; text-align: right">
      <van-button round type="primary" size="small" @click="onEdit">修改</van-button>
      <van-button round type="danger" size="small" @click="onDelete" style="margin-left: 10px;">删除</van-button>
    </div>
  </div>
  <div v-show="vMode === 'edit'">
    <van-nav-bar :title="vRow.name" left-text="返回" left-arrow @click-left="vMode = 'home'" />
    <van-form @submit="onSubmit">
      <van-field v-model="vRowEdit.name" name="name" label="名称" placeholder="名称" required
        :rules="[{ required: true, message: '请填写名称' }]" clearable />
      <van-field v-model="vRowEdit.full_name" name="full_name" label="全称" clearable />
      <van-field v-model="vRowEdit.code_number" name="code_number" label="编号" clearable />
      <van-field name="is_master" label="是否为主体">
        <template #input>
          <van-switch v-model="vRowEdit.is_master" name="is_master" size="20" />
        </template>
      </van-field>
      <van-field v-model="vRowEdit.use_mk" name="use_mk" label="类型">
        <template #input>
          <van-radio-group v-model="vRowEdit.use_mk" direction="horizontal">
            <van-radio name="1">使用中</van-radio>
            <van-radio name="0">未使用</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field v-model="vRow.command" name="command" label="令牌" placeholder="输入内容后提交自动保存" clearable />
      <van-field v-model="vRow.remark" name="remark" rows="2" autosize label="备注" type="textarea" clearable />
      <!-- 公共 popup -->
      <van-popup v-model:show="vSetting._popup" position="bottom">
        <van-picker :columns="vSetting._popupOption" @confirm="onPopupConfirm" @cancel="vSetting._popup = false" />
      </van-popup>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script lang="ts" setup>
import { Wap } from "../../../common/wap";
import {
  showConfirmDialog,
  showFailToast,
  showLoadingToast,
  showSuccessToast,
} from "vant";
import { ref } from "vue";
import type { Ref } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();

const editInit: KvObj = {
  date: Wap.dateFormat(),
  use_mk: 1,
  inout: -1,
};

// 监视值命名
const vList: Ref<Array<KvObj>> = ref([]);
const loading = ref(false);
const finished = ref(false);
const vMode = ref("home");
const vRow: Ref<KvObj> = ref({});
const vRowEdit: Ref<KvObj> = ref(editInit);
const home = ref({
  toolBtn: false,
  tools: [
    { name: "搜索", key: "search" },
    { name: "新增", key: "add" },
  ],
  search: {
    value: "",
    show: false,
  },
});

let _popupOption: Array<KvObj> = [];
let masterCache: Array<KvObj> | null = null;
const vSetting = ref({
  _popupOption,
  _popup: false,
  _showDatePicker: false,
  minDate: new Date(2013, 0, 1),
  maxDate: new Date(),
  masterCache,
  _popupCurKey: "",
});

const cPg = ref({
  current: 0,
  pageSize: 15,
});


// 函数定义
function goHome() {
  router.push({ path: "/finance" });
}

/**
 *
 * @param {object} [postData]
 * @param {boolean} [flushMk]
 */
function loadList(postData?: KvObj | null, flushMk?: boolean) {
  postData = postData || {};
  if (flushMk) {
    cPg.value.current = 1;
  }
  postData = Object.assign({}, cPg.value, postData);
  Wap.post("/square/data/master", postData)
    .then((result) => {
      if (result.status === "ok") {
        let data = result.data;
        let oData = vList.value;
        if (flushMk) {
          oData = [];
        }
        let list = data.list || [];
        if (!list || list.length === 0) {
          finished.value = true;
          loading.value = false;
        } else {
          loading.value = false;
          finished.value = false;
        }
        list = oData.concat(list);
        vList.value = list;
      } else {
        finished.value = true;
        loading.value = false;
        showFailToast(result.msg);
      }
    })
    .catch((error) => {
      console.log(error);
      finished.value = true;
      loading.value = false;
    });
}

function onLoad() {
  cPg.value.current += 1;
  loadList();
}

function onSearch() {
  let { value } = home.value.search;
  let post = {
    s_keyword: "name",
    s_value: value,
  };
  cPg.value = Object.assign({}, cPg.value, post);
  loadList(post, true);
}

function onSearchKeydown(e: any) {
  switch (e.which) {
    case 13:
      home.value.search.show = false;
      onSearch();
      break;
  }
}

// 编辑
function onEdit() {
  const rowData = vRow.value;
  rowData.is_master = !!rowData.is_master;

  vRowEdit.value = rowData;
  vMode.value = "edit";
}

// 删除
function onDelete() {
  showConfirmDialog({
    title: "提示",
    message: "您确定要删除数据吗，删除后不可撤销？",
  }).then(() => {
    // on confirm
    let loading = showLoadingToast({
      duration: 0, // 持续展示 toast
      forbidClick: true,
      message: "数据提交中",
    });
    Wap.post("/square/data/master/del", {
      id: vRowEdit.value.id,
    })
      .then((result) => {
        Wap.resolveResponse(result)
          .then(() => {
            loadList(null, true);
            showSuccessToast(result.msg);
            vMode.value = "list";
          })
          .catch((msg) => {
            showFailToast(msg);
          });
      })
      .finally(() => {
        loading.close();
      });
  });
}

function onHomeToolSel(item: KvObj) {
  let key = item.key;
  switch (key) {
    case "search":
      home.value.search.show = true;
      break;
    case "add":
      vMode.value = "edit";
      break;
  }
}

function onSubmit(values: KvObj) {
  let saveData = Object.assign({}, vRowEdit.value, values);
  saveData.is_master = saveData.is_master ? 1 : 0;

  let loading = showLoadingToast({
    duration: 0, // 持续展示 toast
    forbidClick: true,
    message: "数据提交中",
  });
  Wap.post("/square/data/master/save", saveData)
    .then((result) => {
      Wap.resolveResponse(result)
        .then(() => {
          if (!vRow.value.id) {
            vRowEdit.value.money = "";
          }
          showSuccessToast(result.msg);
          loadList(null, true);
        })
        .catch((msg) => {
          showFailToast(msg);
        });
    })
    .finally(() => {
      loading.close();
    });
}

//确认时处理
function onPopupConfirm(item: KvObj) {
  if (!item) {
    vSetting.value._popup = false;
    return;
  }
  let key = vSetting.value._popupCurKey;
  switch (key) {
    case "master":
      vRowEdit.value.master = item.text;
      vRowEdit.value.master_id = item.value;
      break;
    case "slave":
      vRowEdit.value.slave = item.text;
      vRowEdit.value.slave_id = item.value;
      break;
  }
  vSetting.value._popup = false;
}
</script>